<template>
  <div class="user-add-pre">
    <ui-form ref="userForm" :model="userForm" :rules="userRules" label-width="150px" label-position="right" class="vx-form mg-top-20">
      <ui-form-item label="登录ID" prop="loginId">
        <ui-input v-model="userForm.loginId" placeholder="请输入登录ID"></ui-input>
      </ui-form-item>
      <ui-form-item label="用户名" prop="userName">
        <ui-input v-model="userForm.userName" maxlength="20" placeholder="请输入用户名"></ui-input>
      </ui-form-item>
      <ui-form-item label="密码" prop="password">
        <ui-input v-model="userForm.password" type="passWord" placeholder="请输入密码"></ui-input>
      </ui-form-item>
      <ui-form-item label="确认密码" prop="confirmPassword">
        <ui-input v-model="userForm.confirmPassword" type="passWord" placeholder="请输入确认密码"></ui-input>
      </ui-form-item>
      <ui-form-item label="邮箱" prop="email">
        <ui-input v-model="userForm.email" placeholder="请输入邮箱"></ui-input>
      </ui-form-item>
      <ui-form-item label="手机号" prop="phone">
        <ui-input v-model="userForm.phone" maxlength="11" placeholder="请输入11位手机号"></ui-input>
      </ui-form-item>
      <ui-form-item label="是否管理员" prop="adminFlag">
        <ui-radio-group v-model="userForm.adminFlag">
          <ui-radio label="1">是</ui-radio>
          <ui-radio label="0">否</ui-radio>
        </ui-radio-group>
      </ui-form-item>
      <ui-form-item label="添加角色" v-if="userForm.adminFlag === '0'">
        <ui-select v-model="userForm.roleIds" placeholder="请选择角色">
          <ui-option v-for="(item, index) in userForm.roleAllList" :key="index" :value="item.id" :label="item.name"></ui-option>
        </ui-select>
      </ui-form-item>
      <ui-form-item label="是否启用" prop="enabled">
        <ui-switch :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" v-model="userForm.enabled" />
      </ui-form-item>
      <div class="text-center mg-top-40">
        <ui-button class="default-btn" @click="$router.go(-1)">返回</ui-button>
        <ui-button class="primary-long-btn" @click="submit" :loading="isBtnLoading">确认</ui-button>
      </div>
    </ui-form>
    <vx-dialog hide-cancel :message="msg" v-model="showDialog"> </vx-dialog>
    <vx-dialog hide-cancel message="添加用户成功" v-model="showDialog2" @confirm="$router.go(-1)"> </vx-dialog>
  </div>
</template>

<script>
import userApi from '@/api/user';
import validate from '@/utils/validate';

// eslint-disable-next-line vue/require-name-property
export default {
  name:"userAdd",
  data() {
    /**
     * @description 校验8到16位数字字母组合
     */
    let cifNoRule = function(rule, value, callback) {
      const prefix = rule.prefix || '';
      const min = rule.min || 8;
      const max = rule.max || 16;
      const regu = /^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9!@#$%^&*_]{8,16}$/;
      if (value && value !== null) {
        if (!regu.test(value)) {
          return callback(new Error(`请输入${min}位到${max}的${prefix}`));
        } else {
          return callback();
        }
      } else {
        return callback();
      }
    };
    /**
     * @description 校验登录Id为纯数字
     */
    let numRule = function(rule, value, callback) {
      const prefix = rule.prefix || '';
      const min = rule.min || 5;
      const max = rule.max || 16;
      const regu = /^[0-9a-zA-Z]{5,16}$/;
      if (value && value !== null) {
        if (!regu.test(value)) {
          return callback(new Error(`请输入${min}位到${max}的${prefix}`));
        } else {
          return callback();
        }
      } else {
        return callback();
      }
    };
    return {
      //添加用户弹框
      userForm: {
        loginId: '', //登录ID
        userName: '', //用户名
        roleAllList: [], //所有角色数据
        roleIds: '',
        enabled: 1, //是否启用
        email: '', //邮箱
        phone: '', //手机号
        password: '', //密码
        confirmPassword: '', //确认密码
        adminFlag: '0',
      },
      msg: '', //弹框内容
      isBtnLoading: false,
      showDialog: false,
      showDialog2: false,
      userRules: {
        loginId: [
          { required: true, message: '请输入登录ID', trigger: ['change', 'blur'] },
          { validator: numRule, trigger: ['change', 'blur'], prefix: '数字、字母组合' },
        ],
        userName: [
          { required: true, message: '请输入用户名', trigger: ['change', 'blur'] },
          { validator: validate.checkAcNameRule, trigger: ['change', 'blur'] },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['change', 'blur'] },
          { validator: cifNoRule, min: 8, max: 16, prefix: '数字、字母组合', trigger: ['change', 'blur'] },
        ],
        confirmPassword: [
          { required: true, message: '请输入密码', trigger: ['change', 'blur'] },
          { validator: cifNoRule, min: 8, max: 16, prefix: '数字、字母组合', trigger: ['change', 'blur'] },
        ],
        email: [
          { required: false, message: '请输入邮箱', trigger: ['change', 'blur'] },
          { validator: validate.emailRule, trigger: ['change', 'blur'] },
        ],
        phone: [
          { required: false, message: '请输入手机号', trigger: ['change', 'blur'] },
          { validator: validate.phoneRule, trigger: ['change', 'blur'] },
        ],
      },
    };
  },

  mounted() {
    this.roleAll();
  },
  /**
   * @description 离开页面清除数据
   */
  beforeDestroy() {
    this.clearData();
  },
  methods: {
    /**
     * @description 查询添加用户下的所有角色信息
     */
    async roleAll() {
      try {
        const res = await userApi.roleAll();
        this.userForm.roleAllList = res.data;
      } catch (error) {
        console.log(error);
      }
    },
    /**
     * @description 提交跳转
     */
    submit() {
      this.$refs['userForm'].validate(async (valid) => {
        // 表单校验通过
        if (valid) {
          if (this.userForm.password !== this.userForm.confirmPassword) {
            this.showDialog = true;
            this.msg = '两次密码输入不一致';
            return;
          }
          if (this.userForm.adminFlag === '0' && this.userForm.roleIds === '') {
            this.showDialog = true;
            this.msg = '请选择角色';
            return;
          }
          try {
            this.isBtnLoading = true;
            //检查登录id是否重复
            await userApi.userCheckUnique(this.userForm.loginId);
            //添加用户接口
            await userApi.userAdd({ ...this.userForm, adminFlag: Number(this.userForm.adminFlag) });
            //不是管理员才需要发此接口
            if (this.userForm.adminFlag === '0') {
              await userApi.userAddRole({ userId: this.userForm.loginId, roleIds: this.userForm.roleIds });
            }
            this.showDialog2 = true;
          } finally {
            this.isBtnLoading = false;
          }
        } else {
          this.$nextTick(() => {
            document
              .querySelectorAll('.is-error')[0]
              .querySelector('input')
              .focus();
          });
        }
      });
    },
  },
};
</script>
